// 获取页面元素
const textElement = document.getElementById('color-text');
const colorPicker = document.querySelector('.color-picker');
const colorInput = document.querySelector('.color-input');

// 颜色选择器事件监听
colorPicker.addEventListener('input', (e) => {
    textElement.style.color = e.target.value;
    colorInput.value = e.target.value; // 同步输入框
});

// 手动输入框事件监听
colorInput.addEventListener('input', (e) => {
    try {
        textElement.style.color = e.target.value;
        colorPicker.value = isValidColor(e.target.value); // 同步颜色选择器
    } catch {
        textElement.style.color = '#000000'; // 错误时恢复默认
    }
});

// 随机颜色功能
function randomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    textElement.style.color = color;
    colorPicker.value = color;
    colorInput.value = color;
}

// 验证颜色有效性
function isValidColor(color) {
    const tempElement = document.createElement('div');
    tempElement.style.color = color;
    return tempElement.style.color ? color : '#000000';
}